<template>
  <t-collapse style="margin: 20px 0">
    <t-collapse-panel
      v-for="_ in transformedData"
      :key="_.value"
      :header="_.label"
    >
      <template #headerRightContent>
        <span v-if="_.confirmTime" style="font-weight: normal;">验收时间：{{ dayjs(_.confirmTime).format('YYYY-MM-DD hh:mm:ss') }}</span>
      </template>
      <upload v-model:files="_.fileUrl" accept="image/*" multiple theme="image" :disabled="_.status==='1'||_.status==='2'" />
      <t-button style="margin-top: 4px;" @click="handleSave(_)" v-if="_.status==='0'" v-permission="['system:inspect:create']">保存</t-button>
      <t-button style="margin-top: 4px;" @click="handleSubmit(_)" v-if="_.id&&_.status==='0'" v-permission="['system:inspect:submit-inspect']">提交</t-button>
      <t-button style="margin-top: 4px;" @click="handleReject(_)" v-if="_.status==='1'" v-permission="['system:inspect:reject-inspect']">退回验收</t-button>
      <t-button style="margin-top: 4px;" @click="handleConfirm(_)" v-if="_.status==='1'" v-permission="['system:inspect:confirm-inspect']">确认验收</t-button>
    </t-collapse-panel>
  </t-collapse>
</template>
<script setup lang="ts">
import dayjs from 'dayjs';
import { inject, onMounted, Ref, ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { inspectListCRUD, engineeringSubmitInspect, engineeringConfirmInspect, engineeringRejectInspect } from '@/api/project/details'
import Upload from '@/components/upload/index.vue';

import { useDictionaryStore } from '@/store';
// 定义 props
const props = defineProps({
  injectKey: {
    type: String,
    default: 'engineeringDetails',
  },
});
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 默认的注入键
const injectKey = props.injectKey
// 动态注入数据
const details = inject<Ref<Record<string, any>>>(injectKey);
// 施工详情
const engineeringDetails = details;
const engineeringId = details.value.engineeringId || details.value.id
const orderId = details.value.orderId || details.value.id
onMounted(() => {
  hanldeGetInspetList();
});
const transformedData = ref<Record<string,any>[]>([])
// 获取验收单
const hanldeGetInspetList = () => {
  inspectListCRUD.page({pageSize:-1,engineeringId:engineeringId}).then(data => {
    transformedData.value = transformData(data.list, dictionaryStore.get('acceptance_form_type'));
    console.log(transformedData.value,'trans');
    
  })
}

const transformData=(dataList: any[], formTypes: any[]) => {
  // 创建默认的返回结果
  const defaultResult = formTypes.map(item => ({
    ...item,
    fileUrl: [],
    status: "0" 
  }));

  if (!Array.isArray(dataList) || dataList.length === 0) {
    return defaultResult;
  }

  // 根据 stage 和 value 匹配，填充 fileUrl
  const result = defaultResult.map(formType => {
    const matchedItem = dataList.find(item => item.stage === formType.value);
    if (matchedItem) {
      return {
        ...formType,
        id: matchedItem.id,
        engineeringId: matchedItem.engineeringId,
        stage: matchedItem.stage,
        status: matchedItem.status,
        fileUrl: JSON.parse(matchedItem.fileUrl),
        confirmTime: matchedItem.confirmTime,
        createTime: matchedItem.createTime
      };
    } else {
      return { ...formType, fileUrl: [],status: "0" };
    }
  });

  return result;
}

// 保存
const handleSave = (row: any) => {
  console.log(row,'row');
  if(row.id) {
    const params = {id:row.id,fileUrl:row.fileUrl}
    inspectListCRUD.update(params).then(res => {
      hanldeGetInspetList()
      MessagePlugin.success("保存成功")
    }).catch(({ message }) => {
      MessagePlugin.error(message);
    });
  } else {
    if(row.fileUrl.length === 0) {
      MessagePlugin.error('请上传图片');
      return
    }
    const params = {stage:row.value,fileUrl:row.fileUrl,engineeringId:engineeringId}
    inspectListCRUD.create(params).then(res => {
      hanldeGetInspetList()
      MessagePlugin.success("保存成功")
    }).catch(({ message }) => {
      MessagePlugin.error(message);
    });
  }
  
}

// 提交
const handleSubmit = (row: any) => {
  const params = {id:row.id, engineeringId:row.engineeringId,}
  engineeringSubmitInspect(params).then(res => {
      hanldeGetInspetList()
      MessagePlugin.success("提交成功")
    }).catch(error => {
      MessagePlugin.error(error.msg)
    })
  
}

// 退回
const handleReject = (row: any) => {
  const params = {id:row.id, engineeringId:row.engineeringId}
  engineeringRejectInspect(params).then(res => {
      hanldeGetInspetList()
      MessagePlugin.success("退回成功")
    }).catch(({ message }) => {
      MessagePlugin.error(message);
    });
  
}
// 确认
const handleConfirm = (row: any) => {
  const params = {id:row.id,engineeringId:row.engineeringId}
  engineeringConfirmInspect(params).then(res => {
      hanldeGetInspetList()
      MessagePlugin.success("确认成功")
    }).catch(({ message }) => {
      MessagePlugin.error(message);
    });
  
}
</script>
